import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:share_fit/app/controllers/base/base_controller.dart';
import 'package:share_fit/app/controllers/home/exercise_records/model/exercise_type.dart';
import 'package:share_fit/app/helper/db/ute_db_helper.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/models/home/date_type_enum.dart';
import 'package:share_fit/app/models/home/workout_model.dart';
import 'package:share_fit/app/routes/home_routes.dart';
import 'package:share_fit/app/routes/sports_routes.dart';
import 'package:share_fit/app/tools/date_tool.dart';
import 'package:share_fit/app/tools/log_utils.dart';
import 'package:share_fit/app/tools/unit_util.dart';
import 'package:share_fit/generated/locales.g.dart';
import 'state.dart';

class ExerciseRecordsLogic extends BaseController {
  final WorkoutRecordsState state = WorkoutRecordsState();

  /// 点击运动记录汇总container下面日期
  void changeDate(date) {
    state.selectedDate = date;
    update(['date_type_container']);

    queryInRange(state.selectedExerciseType, date, dateEnd: date);
  }

  /// 右上角日历选择
  datePicker(dt) {
    if (dt != null) {
      state.selectedDate = dt;
      state.selectedDateType = DateType.day;

      state.dates.clear();
      state.dates.add(dt);

      update(['calendar_btn_icon', 'date_type_container']);

      queryInRange(state.selectedExerciseType, dt, dateEnd: dt);
    }
  }

  /// 返回上一页
  goBack() {
    Get.back();
  }

  /// 点击日、周、月
  void changeDateType({int? selectedIndex, required DateType type}) {
    state.selectedDateType = type;
    state.dateTypeBarIndex = selectedIndex ?? 0;

    if (type == DateType.year) {
      for (var month = 1; month <= 12; month++) {
        // state.dates.add('$month');
      }
    } else if (type == DateType.week) {
      List<DateTime> dts = type.getWeekDays;
      state.dates = dts;
      queryInRange(state.selectedExerciseType, dts.first, dateEnd: dts.last);
    } else if (type == DateType.month) {
      List<DateTime> dts = type.getMonthDays;
      state.dates = dts;
      queryInRange(state.selectedExerciseType, dts.first, dateEnd: dts.last);
    } else {
      DateTime day = state.selectedDate;
      state.dates = [day];
      queryInRange(state.selectedExerciseType, day, dateEnd: day);
    }

    update(['calendar_btn_icon', 'date_type_bar']);
  }

  /// 改变运动类型，全部、跑步、户外跑、健步、其他
  void changeExerciseType(type) {
    state.selectedExerciseType = type;

    DateTime start = state.dates.isEmpty ? state.selectedDate : state.dates[0];
    DateTime end = state.dates.isEmpty ? state.selectedDate : state.dates[state.dates.length - 1];
    queryInRange(state.selectedExerciseType, start, dateEnd: end);
  }

  queryInRange(ExerciseType type, DateTime dateStart, {DateTime? dateEnd}) {
    UteDbHelper.getDB().then((db) {
      String start = DateTool.getYMDStr(dateStart);
      String end = null == dateEnd ? start : DateTool.getYMDStr(dateEnd);
      List<int> types = Type.getTypes(type.type);
      logger2.d('date range in [$start ~ $end], types is ${types.toString()}');
      db.workoutDao.findInRangeByType(getAddress(), types, start, end).then((list) => _onQueryRecords(list));
    });
  }

  _onQueryRecords(List<WorkoutModel> list) {
    Map<String, Iterable<WorkoutModel>> map = {for (var element in list) element.calendar: list.where((item) => item.calendar == element.calendar)};
    List<WorkoutSummaryItem> summaryList = map.entries.map((e) => WorkoutSummaryItem(e.key, List.from(e.value))).toList();
    state.workoutSummary = WorkoutSummary(sessions: 0, distance: 0, summaryList: summaryList);
    update(['workout_list', 'workout_summary']);
  }

  /// 将有运动记录的日期标记在日历上
  onCalendarEventLoad(DateTime day) {
    Map<DateTime, List<bool>> events = LinkedHashMap<DateTime, List<bool>>(
      equals: DateTool.isSameDay,
      hashCode: (key) => key.day * 1000000 + key.month * 10000 + key.year,
    )..addAll(state.dateListOfRecord);

    return events[day] ?? [];
  }

  /// 查找指定年份中有运动记录的日期
  Future<void> _loadDateListOfRecord() async {
    DateTime now = DateTime.now();
    DateTime lastYear = DateUtils.addMonthsToMonthDate(now, -12);
    UteDbHelper.getDB().then((db) => //
        db.workoutDao.findHasRecordDays(getAddress(), DateTool.getYMStr(lastYear), DateTool.getYMDStr(now)).then((result) {
          state.dateListOfRecord.clear();
          result.forEach((element) {
            state.dateListOfRecord.putIfAbsent(DateTime.parse(element), () => [true]);
          });
        }));
  }

  @override
  String getRemotePath() {
    return "";
  }

  @override
  void initState() {
    queryInRange(ExerciseType(Type.all, ''), DateTime.now());
    _loadDateListOfRecord();
  }

  @override
  void onRemoteEvent(event, method) {
    // TODO: implement onRemoteEvent
  }

  goToExerciseDetailPage(WorkoutModel wm) {
    Get.toNamed(SportsRoutes.motionEndPage, arguments: {
      'from': HomeRoutes.exerciseRecordsPage,
      'sportsResult': wm,
      'polyLine': Polyline(
        polylineId: PolylineId((wm.sportId ?? wm.id).toString()),
        points: getPolylinePointList(wm),
        color: Colors.cyan,
        width: 5,
      )
    });
  }

  List<LatLng> getPolylinePointList(WorkoutModel wm) {
      List<LatLng> list = [];

      List source = wm.gpsList;
      if (source.isNotEmpty && source.first.isNotEmpty) {
        for (var map in source.first) {
          var lat = map['gpsLatitude'];
          var lot = map['gpsLongitude'];
          if (lat != null && lat != 0 || lot != null && lot == 0) {
            list.add(LatLng(map['gpsLatitude'], map['gpsLongitude']));
          }
        }
      }
      return list;
  }

  String getLengthUnitString() {
    return UnitUtil.getLengthUnit() == 0 ? LocaleKeys.length_unit_km.ts : LocaleKeys.length_unit_mi.ts;
  }
}
